package com.team.recovery.controller;

import com.team.recovery.domain.dto.RescueRequestDTO;
import com.team.recovery.domain.vo.RescueResponseVO;
import com.team.recovery.service.RescueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 救援相关接口
 */
@RestController
@RequestMapping("/api/rescue")
public class RescueController {

    @Autowired
    private RescueService rescueService;

    /**
     * 用户发起救援请求
     */
    @PostMapping("/request")
    public RescueResponseVO requestRescue(@RequestBody @Valid RescueRequestDTO requestDTO) {
        return rescueService.handleRescueRequest(requestDTO);
    }

    /**
     * 商家接单接口
     */
    @PostMapping("/accept")
    public Map<String, Object> acceptRescue(@RequestParam Long taskId, @RequestParam Long merchantId) {
        boolean success = rescueService.acceptRescue(taskId, merchantId);
        Map<String, Object> resp = new HashMap<>();
        resp.put("success", success);
        resp.put("msg", success ? "接单成功" : "接单失败，订单已被抢或已失效");
        return resp;
    }

    /**
     * WebSocket商家接单接口
     * 客户端发送/app/acceptRescue，消息体包含taskId和merchantId
     */
    @MessageMapping("/acceptRescue")
    @SendTo("/topic/merchant/acceptResult")
    public Map<String, Object> wsAcceptRescue(@Payload Map<String, Object> payload) {
        Long taskId = ((Number)payload.get("taskId")).longValue();
        Long merchantId = ((Number)payload.get("merchantId")).longValue();
        boolean success = rescueService.acceptRescue(taskId, merchantId);
        Map<String, Object> resp = new HashMap<>();
        resp.put("success", success);
        resp.put("msg", success ? "接单成功" : "接单失败，订单已被抢或已失效");
        return resp;
    }

    /**
     * 同步所有商家地理位置到Redis GEO
     */
    @PostMapping("/syncMerchantGeo")
    public Map<String, Object> syncMerchantGeo() {
        rescueService.syncAllMerchantGeoToRedis();
        Map<String, Object> resp = new HashMap<>();
        resp.put("success", true);
        resp.put("msg", "同步成功");
        return resp;
    }
} 